package com.welchapps.nporganizer;

import java.io.File;
import com.welchapps.nporganizer.NotePad;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.parse.ParseObject;

import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;


public class EditorFragment extends Fragment {
	private static final String TAG = "EditorFragment";
		
	private EditText mName, mNote, mBrand, mCollection, mColor, mFinish;
	private Spinner mStatus;
	private ImageButton mImage;
    // The different distinct states the activity can be run in.
    private static final int STATE_EDIT = 0;
    private static final int STATE_INSERT = 1;
    protected Bitmap bm;
    private static int mPageNumber;
    private ViewGroup rootView;

    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateImage = new Runnable() {
        public void run() {
        	mImage.setImageBitmap(bm);
        }
    };
    
    public static EditorFragment create(int pageNumber) {
       EditorFragment fragment = new EditorFragment();
       Bundle args = new Bundle();
       args.putInt("page", pageNumber);
       args.putString("name", (String) NotePad.objects.get(pageNumber + 1).get("name"));
       args.putString("brand", (String) NotePad.objects.get(pageNumber + 1).get("brand"));
       args.putString("collection", (String) NotePad.objects.get(pageNumber + 1).get("collection"));
       args.putString("color", (String) NotePad.objects.get(pageNumber + 1).get("color"));
       args.putString("finish", (String) NotePad.objects.get(pageNumber + 1).get("finish"));
       args.putString("status", (String) NotePad.objects.get(pageNumber + 1).get("status"));
       args.putString("image", (String) NotePad.objects.get(pageNumber + 1).get("image"));
       // to remove null entries
       if (NotePad.objects.get(pageNumber + 1).get("note").equals(null))
    	   args.putString("note", "");
       else
    	   args.putString("note", (String) NotePad.objects.get(pageNumber + 1).get("note"));
       args.putString("ID", (String) NotePad.objects.get(pageNumber + 1).getObjectId());
       fragment.setArguments(args);
       return fragment;
    }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageNumber = getArguments().getInt("page");
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	Log.i(TAG, "Creating view for " + mPageNumber);
    	Bundle args = getArguments();
    	
    	// Setup action bar
    	setHasOptionsMenu(true); 
    	ActionBar actionBar = getActivity().getActionBar();
    	actionBar.setDisplayHomeAsUpEnabled(true);
        rootView = (ViewGroup) inflater.inflate(
                R.layout.note_editor, container, false);
        mName = (EditText) rootView.findViewById(R.id.name);
        mBrand = (EditText) rootView.findViewById(R.id.brand);
        mCollection = (EditText) rootView.findViewById(R.id.coll);
        mColor = (EditText) rootView.findViewById(R.id.color);
        mFinish = (EditText) rootView.findViewById(R.id.finish);
        mStatus = (Spinner) rootView.findViewById(R.id.status);
        mImage = (ImageButton) rootView.findViewById(R.id.photo);
        mNote = (EditText) rootView.findViewById(R.id.notes);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.status, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        mStatus.setAdapter(adapter);
//        if (EditorActivity.mCursor != null) {
            // Requery in case something changed while paused (such as the title)
//        	EditorActivity.mCursor.requery();
            // Make sure we are at the one and only row in the cursor.
//        	EditorActivity.mCursor.moveToPosition(mPageNumber);

            // Modify our overall title depending on the mode we are running in.
            if (EditorActivity.mState == STATE_EDIT) {
                // Set the title of the Activity to include the note title
//                String name = EditorActivity.mCursor.getString(1);
//            	NotesList.query.setSkip(mPageNumber);
//            	ParseObject NP; // = new ParseObject;
//            	String name = "null";
//            	NP = ParseObject.createWithoutData("nailPoish", DataCount.OBJECTID.get(mPageNumber));
//            	final String ID = DataCount.OBJECTID.get(mPageNumber + 1);
                Resources res = getResources();
                // setTitle("Edit");              
                if (!res.getString(android.R.string.untitled).equals(args.getString("name"))){
                	mName.setText(args.getString("name"));
                	// CurrentValues.putString("name",name);
	                mBrand.setText(args.getString("brand"));
	                mCollection.setText(args.getString("collection"));
	                mColor.setText(args.getString("color"));
	                mFinish.setText(args.getString("finish"));
	                mStatus.setSelection(adapter.getPosition(args.getString("finish")));
	                mNote.setText(args.getString("note"));
                }
                dispImage();

            } else if (EditorActivity.mState == STATE_INSERT) {
                
            }
//            
//        }
        
        // Click listener for image button
        mImage.setOnClickListener(new ImageButton.OnClickListener() {

            public void onClick(View view) {
            	
              registerForContextMenu(view); 
              getActivity().openContextMenu(view);
              unregisterForContextMenu(view);
          	  	
            }
        });
        
        
        return rootView;
    }
             
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Inflate menu from XML resource
        inflater.inflate(R.menu.editor_options_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
        	getActivity().finish();
        	//cancelNote(null);
        	return true;
        case R.id.menu_save:
            // Launch activity to insert a new item
            saveNote();
            return true;
        case R.id.menu_revert:
        	getActivity().finish();
        	//cancelNote(null);
            return true;
        	
        case R.id.menu_delete:
        	//deleteButton(null);
            return true;     
        case R.id.menu_discard:
//        	if (imgfile != null) {
//        		File file = new File(imgfile);
//        		file.delete();
//        		mImage.setImageResource(R.drawable.camera_button);
//        		imgfile = "null";
//        	}
        	return true;        
        default:
            return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getActivity().getMenuInflater();
        if (getArguments().getString("image").equals("")){
        	inflater.inflate(R.menu.image_context_menu2, menu);
        }else{
        	inflater.inflate(R.menu.image_context_menu1, menu);
        }

    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        File file;
        switch (item.getItemId()) {
        	case R.id.context_view:
        		Intent intent = new Intent();  
        		if(getArguments().getString("image").contains("http")){
        			intent.setAction(Intent.ACTION_VIEW);
        			intent.setData(Uri.parse(getArguments().getString("image")));
        		}else{
        			intent.setAction(android.content.Intent.ACTION_VIEW);  
	        		file = new File(getArguments().getString("image"));  
	        		intent.setDataAndType(Uri.fromFile(file), "image/*");  
        		}
        		startActivity(intent);
        		return true;        
            case R.id.context_capture:
				try {
					file = createImageFile();    	        
					Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	    	    	takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
	    	        startActivityForResult(takePictureIntent, 0);
	    	        getArguments().putString("image", file.toString()); // = file.toString();
	    	        dispImage();
				} catch (IOException e) {
					 Toast.makeText(getActivity(), "Unable to open output file. Check SD card." , Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
                return true;
            case R.id.context_gallery:
            	Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            	photoPickerIntent.setType("image/*");
            	startActivityForResult(photoPickerIntent, 100); 
                return true;
            case R.id.context_delete:
            	if(getArguments().getString("image").contains("com.welchapps.nporganizer")){
	        		file = new File(getArguments().getString("image"));
	        		file.delete();
            	}
        		mImage.setImageResource(R.drawable.camera_button);
        		getArguments().putString("image", "");
                return true;
            case R.id.context_url:
            	// enterURL();
            	dispImage();
            	return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    public void dispImage(){
    	new Thread (){
    		public void run(){
    			String imgFile = getArguments().getString("image");
    	    	DisplayMetrics metrics = getResources().getDisplayMetrics();
    	    	int width = metrics.widthPixels;  
    	    	int scale;
    	        BitmapFactory.Options optionsDecode = new BitmapFactory.Options();
    	        BitmapFactory.Options options = new BitmapFactory.Options();
    	        // options.inSampleSize = 4; 
    	        if(imgFile.contains("null")){
    	        	
    	        }
    	        else if(imgFile.contains("http")){
    	        	// Place loading symbol
    	        	bm = BitmapFactory.decodeResource(getResources(), R.drawable.loading);
    	        	mHandler.post(mUpdateImage);
    	        	URL url;
    				try {
    					url = new URL(imgFile);
    	            	optionsDecode.inJustDecodeBounds = true;
    	            	BitmapFactory.decodeStream(url.openConnection().getInputStream(), null ,optionsDecode);  
    	            	if (optionsDecode.outWidth < width){
    	            		scale = 1;
    	            	}
    	            	else{
    	            		scale = (optionsDecode.outWidth / width) + 4;
    	            	}
    	            	options.inSampleSize = scale;
    	            	bm = BitmapFactory.decodeStream(url.openConnection().getInputStream(), null ,options);  
    	            	mHandler.post(mUpdateImage);
    	                //if (bm != null) mImage.setImageBitmap(bm);
    				} catch (MalformedURLException e) {
    					Toast.makeText(getActivity(), "Unable to open URL", Toast.LENGTH_SHORT).show();
    					// imgFile = "NA";
    					e.printStackTrace();
    				} catch (IOException e) {
    					e.printStackTrace();
    					Toast.makeText(getActivity(), "Unable to open URL", Toast.LENGTH_SHORT).show();
//    					imgFile = "NA";
    				}

    	        }else{
    	        	optionsDecode.inJustDecodeBounds = true;
    	        	BitmapFactory.decodeFile(imgFile, optionsDecode);  
	            	if (optionsDecode.outWidth < width){
	            		scale = 1;
	            	}
	            	else{
	            		scale = (optionsDecode.outWidth / width);
	            	}
    	        	options.inSampleSize = scale;
    	        	bm = BitmapFactory.decodeFile(imgFile, options);  
    	            if (bm != null) mHandler.post(mUpdateImage);
//    	            else imgfile = "NA";
    	        }
    		}
    	}.start();

    }
    
    private void saveNote(){
    	if (EditorActivity.mState == STATE_EDIT) {
	    	// Notify that query has change
	    	/**********************************************/
	    	// Check for changes and do nothing if no changes otherwise save note
	    	if(newValues()){
	    		String ID = getArguments().getString("ID");
	    		Log.i(TAG, "Saving new values to ID " + ID);
	    		ParseObject object = new ParseObject ("nailPolish");
	    		object.setObjectId(ID);
	    		object.put("name", mName.getText().toString().trim());
	    		object.put("brand", mBrand.getText().toString().trim());
	    		object.put("collection", mCollection.getText().toString().trim());
	    		object.put("color", mColor.getText().toString().trim());
	    		object.put("finish", mFinish.getText().toString().trim());
	    		object.put("status", mStatus.getSelectedItem().toString().trim());
	    		object.put("note", mNote.getText().toString().trim());
	    		object.saveInBackground();
	    		
	    		// Alert to requery
	    		NotePad.Requery = true;
	    	}
	    	else
	    		Log.w(TAG, "No new values to save");
	    	}
    	else {
    		ParseObject object = new ParseObject ("nailPolish");
    		String ID = object.getObjectId();
    		object.setObjectId(ID);
    		Log.i(TAG, "Saving new values to ID " + ID);
    		object.put("name", mName.getText().toString().trim());
    		object.put("brand", mBrand.getText().toString().trim());
    		object.put("collection", mCollection.getText().toString().trim());
    		object.put("color", mColor.getText().toString().trim());
    		object.put("finish", mFinish.getText().toString().trim());
    		object.put("status", mStatus.getSelectedItem().toString().trim());
    		object.put("note", mNote.getText().toString().trim());
    		object.saveInBackground();
    		
    		// Alert to requery
    		NotePad.Requery = true;
    		
    	}
//    	ParseObject nailPolish = new ParseObject("nailPolish");
//    	nailPolish.put("name", mName.getText().toString().trim());
//    	nailPolish.setACL(new ParseACL(ParseUser.getCurrentUser()));
//    	nailPolish.saveInBackground();
    }
    
    private File createImageFile() throws IOException{
        // Create an image file name
        String timeStamp = 
            new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "image" + timeStamp + "_";
        File image = File.createTempFile(
            imageFileName, 
            ".jpg", 
            getActivity().getExternalFilesDir(null)
        );
        // mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
    
    private boolean newValues (){
    	Bundle args = getArguments();
    	if (!mName.getText().toString().trim().equals(args.getString("name")))
    		return true;
    	if (!mBrand.getText().toString().trim().equals(args.getString("brand")))
    		return true;
    	if (!mCollection.getText().toString().trim().equals(args.getString("collection")))
    		return true;
    	if (!mColor.getText().toString().trim().equals(args.getString("color")))
    		return true;
    	if (!mFinish.getText().toString().trim().equals(args.getString("finish")))
    		return true;
    	if (!mStatus.getSelectedItem().toString().trim().equals(args.getString("status")))
    		return true;
    	return false;
    	
    }
}
    
